import { _decorator, Component, Node, Button, Label } from 'cc';
import { Sprite } from 'cc';
import { color } from 'cc';
import { BaseView } from '../../../../scripts/libs/rxjs/cc3/BaseView';
import { ReactiveNumber } from '../../../../scripts/libs/rxjs/cc3/ReactiveNumber';
import { ReactiveProperty } from '../../../../scripts/libs/rxjs/cc3/ReactiveProperty';
import { BindButton } from '../../../../scripts/libs/rxjs/cc3/BindButton';
import { gm } from '../../../../scripts/managers/GameManager';
import { Colors } from '../../game/basic';
const { ccclass, property, executeInEditMode } = _decorator;

@ccclass('ColorEditorButton')
@executeInEditMode
export class ColorEditorButton extends BaseView {

    @property(ReactiveNumber)
    _colorId: ReactiveNumber = ReactiveNumber.DefaultValue(0);
    @property
    get colorId(): number { return this._colorId.value }
    set colorId(v: number) { this._colorId.Value = v; }

    checked = ReactiveProperty.Create(false);

    @property(Button)
    selfButton: Button = null;

    @property(Label)
    idLabel: Label = null;

    useObserves() {
        return [
            this._colorId.subscribe(this.refreshColor.bind(this)),
            this.checked.subscribe(this.refreshChecked.bind(this)),
            BindButton(this.selfButton).subscribe(this.selfButtonClicked.bind(this)),
            gm.editColorSelected.subscribe(_ => {
                this.checked.value = this.colorId == gm.editColorSelected.value;
            }),
        ];
    }

    refreshColor() {
        this.getComponent(Sprite).color = Colors[this.colorId] ?? color(0, 0, 0);
        this.idLabel.string = this.colorId.toString();
    }

    refreshChecked() {
        this.node.getChildByName('Checked').active = this.checked.value;
    }

    selfButtonClicked() {
        gm.editColorSelected.value = this.colorId;
    }

}


